package com.effectiv.gooruda.rest.ext;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import jodd.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.codec.binary.Base64;



@Slf4j
public class PasswordEncoder {
	
	public static String encode(String secret, String salt){
		Mac sha256_HMAC = null;
		String hash = null;
		try {
			sha256_HMAC = Mac.getInstance("HmacSHA256");
			SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(),
					"HmacSHA256");
			sha256_HMAC.init(secret_key);

			hash = Base64.encodeBase64String(sha256_HMAC.doFinal(salt
					.getBytes()));
		} catch (NoSuchAlgorithmException e) {
			log.error("No such algorithm", e);
		} catch (InvalidKeyException e) {
			log.error("Invalid key", e);
		}
		
		log.info("Hash = {}", hash);
		
		return hash;
	}
	
	public static boolean isPasswordValid(String retrivedPwd, String suppliedPwd, String salt){
		String hashedPwd = encode(suppliedPwd, salt);
		
		return StringUtil.equals(hashedPwd, retrivedPwd);
	}
}
